local sqlite = require("asyncsql4lua").sqlite

local function connect(database)
    local inner_fn = coroutine.wrap(
        function()
            sqlite:connect(database)
        end
    )
    while true do
        if inner_fn() == nil then 
            break
        end
    end
end

local function execute(sql)
    local res
    local inner_fn = coroutine.wrap(
        function()
            res = sqlite:execute(sql)
        end
    )
    while true do
        if inner_fn() == nil then 
            break
        end
    end
    return res
end

local function query(sql)
    local res
    local inner_fn = coroutine.wrap(
        function()
            res = sqlite:query(sql)
        end
    )
    while true do
        if inner_fn() == nil then
            break
        end
    end
    return res
end

local function main()
    connect("test.db")
    
    -- Create table if not exists
    execute([[
        CREATE TABLE IF NOT EXISTS 
        users (
        id INTEGER PRIMARY KEY AUTOINCREMENT, 
        name TEXT, 
        age INTEGER, 
        email TEXT, 
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
    ]])


    local res = execute([[
        INSERT INTO 
        users
        (name, age, email)
        VALUES
        ('Li', 20, 'li@gmail.com'),
        ('Shang', 21, 'shang@email.com'),
        ('Wu', 30, 'wu@163.com')
    ]])

    print("rows_affected: " .. res.rows_affected .. ", last_insert_id: " .. res.last_insert_id)

    local res = query("SELECT * FROM users")
    for _, user in pairs(res) do
        print(user.id, user.name, user.age, user.created_at)
    end
end
main()